﻿using UnityEngine;

namespace TinyAsset
{
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        static T __instance;

        public static T Instance
        {
            get
            {
                if (__instance == null)
                {
                    GameObject go = new GameObject(typeof(T).Name);
                    __instance = go.AddComponent<T>();
                }
                return __instance;
            }
        }

        void Awake()
        {
            if (__instance == null)
            {
                __instance = this as T;
                DontDestroyOnLoad(this);
                Awaking();
            }
            else
                DestroyImmediate(this);
        }

        public virtual void Awaking() { }

        public void DestroySingleton()
        {
            if (__instance != null)
            {
                DestroyImmediate(__instance);
                __instance = null;
            }
        }
    }
}